package com.example.question.list.list1;

/**
 * @Date 2023-07-03
 * @Author Jonathan
 * @link {<a href="https://leetcode.cn/problems/remove-duplicates-from-sorted-list/">...</a>}
 */
public class Code03_83 {
    public static void main(String[] args) {
        ListNode head = List.createList(new int[]{1, 1, 1, 2, 2, 2});
        List.printLink(head);
        Code03_83 code = new Code03_83();
        ListNode node = code.deleteDuplicates(head);
        List.printLink(node);
    }


    /**
     * 删除重复元素 链表升序排序
     */
    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummyHead = new ListNode(Integer.MIN_VALUE, head);
        ListNode slow = dummyHead;
        ListNode fast = slow.next;
        while (fast != null) {
            if (slow.val == fast.val) {
                do {
                    // -1,1,1,1,2,2,2
                    slow.next = fast.next;
                    fast = fast.next;
                } while (fast != null && slow.val == fast.val);
            }
            if (fast == null) {
                break;
            }
            slow = fast;
            fast = fast.next;
        }
        return dummyHead.next;
    }

    /**
     * 主要还是思路搞清楚
     */
    public ListNode deleteDuplicates1(ListNode head) {
        ListNode dummyHead = new ListNode(Integer.MIN_VALUE, head);
        ListNode slow = dummyHead;
        ListNode fast = slow.next;
        while (fast != null) {
            if (fast.val == slow.val) {
                slow.next = fast.next;
                fast.next = null;
            } else {
                slow = slow.next;
            }
            fast = slow.next;
        }
        return dummyHead.next;
    }
}
